<?php

namespace App\Admin\Actions\Post;

use App\Http\Controllers\CommonController;
use App\Models\PersonalUser;
use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use DB;

class AllJobMoney extends BatchAction
{
    public $name = '批量结算';

    public function handle(Collection $collection)
    {
        foreach ($collection as $model) {
            $status = $model->job_status;
            if (!in_array($status, [30])) {
                continue;
            }

            $id = $model->id;
            $total = $model->total;

            $relist = DB::table('resume_send as log')
                ->join('resume as t1', 'log.personal_uid', '=', 't1.uid')
                ->join('company_job as t2', 'log.job_id', '=', 't2.id')
                ->select('log.personal_uid')
                ->where('log.job_id', $id)
//            ->where('log.status', 2)
                ->orderBy('log.created_at', 'DESC')
                ->get()->toArray();

            $intlist = DB::table('interview as log')
                ->join('resume as t1', 'log.personal_uid', '=', 't1.uid')
                ->join('company_job as t2', 'log.job_id', '=', 't2.id')
                ->select('log.personal_uid')
                ->where('log.job_id', $id)
//            ->where('log.status', 2)
                ->orderBy('updated_at', 'DESC')
                ->get()->toArray();

            $list = array_merge($relist, $intlist);
            $uinfo = $list[0];
            $user = PersonalUser::where('uid', $uinfo->personal_uid)->select('hasmoney', 'allmoney')->first();

            $data = [
                'hasmoney' => $user->hasmoney + $total,
                'allmoney' => $user->allmoney + $total
            ];

            $res = PersonalUser::where('uid', $uinfo->personal_uid)->update($data);
            if ($res) {

                $hasmoney = PersonalUser::where('uid', $uinfo->personal_uid)->value('hasmoney');
                $type = array('recordtype' => 1, 'changetype' => 1, 'moneytype' => 1);
                $moneyArr = array('money' => $total, 'hasmoney' => $hasmoney);

                $common = new CommonController();
                $common->money_change($type, 0, $uinfo->personal_uid, $moneyArr, $id);
                unset($type, $moneyArr);

                $model::where('id', $id)->update(['job_status' => 40]);

            } else {
                return $this->response()->error('操作失败！')->refresh();
            }
        }

        return $this->response()->success('操作成功')->refresh();
    }

    public function dialog()
    {
        $this->confirm('确定结算吗？');
    }

}